package com.kuqi.http;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpHelper {


    /**
     * 判断是否连接到服务器
     */
    public static boolean isConnByHttp(String urlStr){
        boolean isConn = false;
        URL url;
        HttpURLConnection conn = null;
        try {
            url = new URL(urlStr);
            conn = (HttpURLConnection)url.openConnection();
            conn.setConnectTimeout(1000*3);
            int s=conn.getResponseCode();

            if(conn.getResponseCode()==200){
                isConn = true;
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            if(conn != null) {
                conn.disconnect();
            }
        }
        return isConn;
    }



    /**
     * 发送json信息到服务端
     * @param urlStr 接受string的接口
     * @param jsonStr 需要发送的json数据
     * @return 服务器反馈的json信息
     */
    public static String PostJsonString(String urlStr,String jsonStr){
        try {
            URL url=new URL(urlStr);
            HttpURLConnection connect=(HttpURLConnection)url.openConnection();
            connect.setDoInput(true);
            connect.setDoOutput(true);
            connect.setRequestMethod("POST");
            connect.setUseCaches(false);
            connect.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            OutputStream outputStream = connect.getOutputStream();
            outputStream.write(jsonStr.getBytes());
            int response = connect.getResponseCode();
            if (response== HttpURLConnection.HTTP_OK)
            {
                System.out.println("server code:" + response);
                InputStream input=connect.getInputStream();
                BufferedReader in = new BufferedReader(new InputStreamReader(input));
                String line = null;
                StringBuilder sbf = new StringBuilder();
                while ((line = in.readLine()) != null) {
                    sbf.append(line);
                }
                return sbf.toString();
            }
            else {
                System.out.println("server code:" + response);
                return "HttpURLConnection do not show ok ! check <PostJsonString> function";
            }
        } catch (Exception e) {
            Log.e("e:", String.valueOf(e));
            return e.toString();
        }
    }

}
